<template>
  <div class="my-bookings-page">
    <h2>🧾 我的订单</h2>

    <section class="all-bookings-section">
      <h3>📋 所有预约订单</h3>

      <div class="filter-controls">
        <label for="statusFilter">筛选订单状态:</label>
        <select id="statusFilter" v-model="selectedStatusFilter">
          <option value="all">所有状态</option>
          <option value="0">已预约未支付</option>
          <option value="1">已支付未使用</option>
          <option value="2">已退款</option>
          <option value="3">未支付，订单失效</option>
          <option value="4">正在退款待审核</option>
          <option value="5">已支付使用中</option>
          <option value="6">订单完成</option>
        </select>
      </div>

      <div v-if="filteredBookings.length === 0" class="no-bookings">
        <img src="https://img.icons8.com/ios/100/empty-box.png" alt="暂无订单" />
        暂无符合条件的预约订单。
      </div>

      <ul v-else class="booking-list">
        <li
          v-for="booking in sortedBookings"
          :key="booking.orderId"
          class="booking-item"
          :class="getBookingStatusClass(booking)"
        >
          <div class="booking-details">
            <p><strong>订单ID:</strong> {{ booking.orderId }}</p>
            <p><strong>会议室:</strong> {{ booking.roomName }}</p>
            <p><strong>时间:</strong> {{ formatDateTime(booking.startTime) }} - {{ formatDateTime(booking.endTime) }}</p>
            <p><strong>总金额:</strong> ¥{{ booking.totalFee }}</p>
            <p><strong>订单状态:</strong> <span class="status-tag" :class="getBookingStatusClass(booking)">
              {{ getBookingStatusText(booking) }}
            </span></p>
          </div>

          <div class="booking-actions">
            <button class="action-button view" @click="viewBookingDetails(booking.orderId)">
              🔍 查看
            </button>
            <button
              v-if="canCancel(booking)"
              class="action-button cancel"
              @click="handleCancelBooking(booking.orderId)"
            >
              ❌ 取消
            </button>
            <button
              v-if="canComment(booking)"
              class="action-button comment"
              @click="handleCommentOrder(booking.orderId, booking.roomId)"
            >
              💬 评价
            </button>
            <button
              v-if="canReportMaintenance(booking)"
              class="action-button report"
              @click="handleReportMaintenance(booking.orderId, booking.roomId)"
            >
              🛠️ 报修
            </button>
          </div>
        </li>
      </ul>
    </section>

    <RefundConfirmationModal
      :is-visible="showRefundModal"
      :refund-rules="refundRulesText"
      @confirm="handleModalConfirm"
      @cancel="handleModalCancel"
    />

    <MessageModal
      :is-visible="showMessageModal"
      :title="messageModalTitle"
      :message="messageModalContent"
      :type="messageModalType"
      @close="handleMessageModalClose"
    />

    <CommentFormModal
      :is-visible="showCommentModal"
      :order-id="selectedOrderIdForComment"
      :room-id="selectedRoomIdForComment"
      @submit="handleCommentSubmit"
      @cancel="handleCommentCancel"
    />

    <MaintenanceReportModal
      :is-visible="showMaintenanceModal"
      :order-id="selectedOrderIdForMaintenance"
      :room-id="selectedRoomIdForMaintenance"
      @submit="handleMaintenanceSubmit"
      @cancel="handleMaintenanceCancel"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getOrdersByUserId, updateOrderStatusWithRefund } from '@/apis/orders';
import { saveCommentAfterOrder } from '@/apis/comment'; // Import the new API
import { reportMaintenance } from '@/apis/maintenance'; // Import the new API
import { useUserStore } from '@/stores/user';
import RefundConfirmationModal from '@/components/global/RefundConfirmationModal.vue';
import MessageModal from '@/components/global/MessageModal.vue';
import CommentFormModal from '@/components/common/CommentFormModal.vue'; // Import the new component
import MaintenanceReportModal from '@/components/common/MaintenanceReportModal.vue'; // Import the new component

const router = useRouter();
const allBookings = ref([]);
const userStore = useUserStore();
const userId = computed(() => userStore.user?.id);
const selectedStatusFilter = ref('all');

const showRefundModal = ref(false);
const selectedOrderIdForRefund = ref(null);
const refundRulesText = ref('');

const showMessageModal = ref(false);
const messageModalTitle = ref('');
const messageModalContent = ref('');
const messageModalType = ref('info');

const showCommentModal = ref(false);
const selectedOrderIdForComment = ref(null);
const selectedRoomIdForComment = ref(null);

const showMaintenanceModal = ref(false);
const selectedOrderIdForMaintenance = ref(null); // Add this line
const selectedRoomIdForMaintenance = ref(null);

// Helper to parse date strings
const parseDateTime = (dtString) => new Date(dtString); // ISO 8601 format from API

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '';
  const date = new Date(dateTimeString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

// Determine booking status text based on paymentStatus
const getBookingStatusText = (booking) => {
  switch (booking.paymentStatus) {
    case 0: return '已预约未支付';
    case 1: return '已支付未使用';
    case 2: return '已退款';
    case 3: return '未支付，订单失效';
    case 4: return '正在退款待审核';
    case 5: return '已支付使用中';
    case 6: return '订单完成';
    default: return '未知状态';
  }
};

// Determine booking status class for styling
const getBookingStatusClass = (booking) => {
  switch (booking.paymentStatus) {
    case 0: return 'status-pending-payment'; // 已预约未支付
    case 1: return 'status-paid-unused'; // 已支付未使用
    case 2: return 'status-refunded'; // 已退款
    case 3: return 'status-invalid'; // 未支付，订单失效
    case 4: return 'status-pending-refund'; // 正在退款待审核
    case 5: return 'status-in-use'; // 已支付使用中
    case 6: return 'status-completed-order'; // 订单完成
    default: return '';
  }
};

// Check if an order can be cancelled
const canCancel = (booking) => {
  // Only allow cancellation if status is '已预约未支付' (0) or '已支付未使用' (1)
  return booking.paymentStatus === 0 || booking.paymentStatus === 1;
};

// Check if an order can be commented on
const canComment = (booking) => {
  // Only allow commenting if status is '订单完成' (6)
  return booking.paymentStatus === 6;
};

// Check if an order can be reported for maintenance
const canReportMaintenance = (booking) => {
  // Only allow reporting maintenance if status is '订单完成' (6)
  return booking.paymentStatus === 6;
};

// Filter bookings based on selected status
const filteredBookings = computed(() => {
  if (selectedStatusFilter.value === 'all') {
    return allBookings.value;
  }
  return allBookings.value.filter(booking => booking.paymentStatus === parseInt(selectedStatusFilter.value));
});

// Sort bookings: prioritize by status, then by start time
const sortedBookings = computed(() => {
  const orderMap = {
    0: 1, // 已预约未支付 - highest priority for action
    4: 2, // 正在退款待审核
    1: 3, // 已支付未使用
    5: 4, // 已支付使用中
    6: 5, // 订单完成
    2: 6, // 已退款
    3: 7, // 未支付，订单失效 - lowest priority
  };

  return [...filteredBookings.value].sort((a, b) => {
    const statusOrderA = orderMap[a.paymentStatus] || 99; // Unknown status last
    const statusOrderB = orderMap[b.paymentStatus] || 99;

    if (statusOrderA !== statusOrderB) {
      return statusOrderA - statusOrderB;
    }

    // For same status, sort by start time (descending for upcoming, ascending for past)
    const startTimeA = parseDateTime(a.startTime);
    const startTimeB = parseDateTime(b.startTime);
    return startTimeB.getTime() - startTimeA.getTime(); // Newest first for same status
  });
});

// Handle cancel booking
const viewBookingDetails = (orderId) => {
  router.push({ name: 'BookingDetails', params: { id: orderId } });
};

const handleCancelBooking = (orderId) => {
  selectedOrderIdForRefund.value = orderId;
  refundRulesText.value = `若放弃使用会议室，需要提前 24 小时申请取消预约，提前 72 小时退全款；提前 48 小时退 75%，提前 24 小时退 25%`;
  showRefundModal.value = true;
};

const handleCommentOrder = (orderId, roomId) => {
  selectedOrderIdForComment.value = orderId;
  selectedRoomIdForComment.value = roomId;
  showCommentModal.value = true;
};

const handleCommentSubmit = async (commentData) => {
  showCommentModal.value = false;
  try {
    // commentData 现在包含 orderId, roomId, content, 和 rating
    const response = await saveCommentAfterOrder(commentData);
    if (response.code === 200) {
      messageModalTitle.value = '评价成功';
      messageModalContent.value = response.data;
      messageModalType.value = 'success';
      await fetchBookings(); // Refresh the list to update UI if needed
    } else {
      messageModalTitle.value = '评价失败';
      messageModalContent.value = `${response.msg || '未知错误'}${response.data ? `\n原因: ${response.data}` : ''}`;
      messageModalType.value = 'error';
    }
  } catch (error) {
    console.error('保存评论失败:', error);
    messageModalTitle.value = '评价失败';
    messageModalContent.value = '保存评论时发生错误，请稍后再试。';
    messageModalType.value = 'error';
  } finally {
    showMessageModal.value = true;
  }
};

const handleCommentCancel = () => {
  showCommentModal.value = false;
  selectedOrderIdForComment.value = null;
  selectedRoomIdForComment.value = null;
};

const handleModalConfirm = async () => {
  showRefundModal.value = false;
  if (!selectedOrderIdForRefund.value) {
    messageModalTitle.value = '错误';
    messageModalContent.value = '未选择订单进行取消。';
    messageModalType.value = 'error';
    showMessageModal.value = true;
    return;
  }

  try {
    const response = await updateOrderStatusWithRefund(selectedOrderIdForRefund.value);
    if (response.code === 200) {
      messageModalTitle.value = '订单取消成功';
      messageModalContent.value = response.data;
      messageModalType.value = 'success';
      await fetchBookings(); // Refresh the list
    } else {
      messageModalTitle.value = '取消订单失败';
      messageModalContent.value = `${response.msg || '未知错误'}${response.data ? `\n原因: ${response.data}` : ''}`;
      messageModalType.value = 'error';
    }
  } catch (error) {
    console.error('取消订单失败:', error);
    messageModalTitle.value = '取消订单失败';
    messageModalContent.value = '取消订单时发生错误，请稍后再试。';
    messageModalType.value = 'error';
  } finally {
    selectedOrderIdForRefund.value = null;
    showMessageModal.value = true;
  }
};

const handleModalCancel = () => {
  showRefundModal.value = false;
  selectedOrderIdForRefund.value = null;
};

const handleMessageModalClose = () => {
  showMessageModal.value = false;
  messageModalTitle.value = '';
  messageModalContent.value = '';
  messageModalType.value = 'info';
};

const handleReportMaintenance = (orderId, roomId) => {
  selectedOrderIdForMaintenance.value = orderId;
  selectedRoomIdForMaintenance.value = roomId;
  showMaintenanceModal.value = true;
};

const handleMaintenanceSubmit = async (problemDescData) => {
  showMaintenanceModal.value = false;
  try {
    const fullReportData = {
      userId: userId.value,
      roomId: selectedRoomIdForMaintenance.value,
      problemDesc: problemDescData.problemDesc
    };
    const response = await reportMaintenance(fullReportData);
    if (response.code === 200) {
      messageModalTitle.value = '报修成功';
      messageModalContent.value = response.data;
      messageModalType.value = 'success';
      await fetchBookings(); // Refresh the list if needed
    } else {
      messageModalTitle.value = '报修失败';
      messageModalContent.value = `${response.msg || '未知错误'}${response.data ? `\n原因: ${response.data}` : ''}`;
      messageModalType.value = 'error';
    }
  } catch (error) {
    console.error('提交报修失败:', error);
    messageModalTitle.value = '报修失败';
    messageModalContent.value = '提交报修时发生错误，请稍后再试。';
    messageModalType.value = 'error';
  } finally {
    showMessageModal.value = true;
  }
};

const handleMaintenanceCancel = () => {
  showMaintenanceModal.value = false;
  selectedRoomIdForMaintenance.value = null;
};

const fetchBookings = async () => {
  if (!userId.value) {
    console.error('User ID is not available.');
    allBookings.value = [];
    return;
  }
  try {
    const response = await getOrdersByUserId(userId.value);
    if (response.code === 200 && response.data) {
      // Flatten the data structure to make order properties directly accessible
      allBookings.value = response.data.map(item => ({
        ...item.order,
        roomName: item.roomName,
        roomType: item.roomType
      }));
    } else {
      console.error('Failed to fetch bookings:', response.msg);
      allBookings.value = [];
    }
  } catch (error) {
    console.error('Failed to fetch bookings:', error);
    allBookings.value = [];
  }
};

onMounted(fetchBookings);
</script>

<style scoped>
.my-bookings-page {
  padding: 2rem;
  /* max-width: 900px; */
  margin: 0 auto;
  font-family: 'Arial', sans-serif;
}

h2 {
  color: #333;
  text-align: center;
  margin-bottom: 2rem;
}

section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h3 {
  color: #0056b3;
  margin-top: 0;
  margin-bottom: 1rem;
  border-bottom: 2px solid #eee;
  padding-bottom: 0.5rem;
}

.no-bookings {
  color: #666;
  text-align: center;
  padding: 1rem;
  background-color: #e9e9e9;
  border-radius: 4px;
}

.booking-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.booking-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 1rem;
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.booking-details {
  flex-grow: 1;
}

.booking-item p {
  margin: 0.2rem 0;
  color: #555;
  font-size: 0.95rem;
}

.booking-item p strong {
  color: #333;
}

.status-tag {
  display: inline-block;
  padding: 0.3em 0.6em;
  border-radius: 4px;
  font-size: 0.85em;
  font-weight: bold;
  color: #fff;
}

.status-pending-payment { background-color: #F44336; color: #FFFFFF; } /* 0=已预约未支付 (标准红，白字) */
.status-paid-unused { background-color: #2196F3; color: #FFFFFF; } /* 1=已支付未使用 (标准蓝，白字) */
.status-refunded { background-color: #9E9E9E; color: #FFFFFF; } /* 2=退款 (中灰，白字) */
.status-invalid { background-color: #607D8B; color: #FFFFFF; } /* 3=未支付，订单失效 (蓝灰，白字) */
.status-pending-refund { background-color: #FFC107; color: #212121; } /* 4=正在退款待审核 (琥珀黄，深灰字 - 保持原样，对比度尚可) */
.status-in-use { background-color: #00BCD4; color: #FFFFFF; } /* 5=已支付使用中 (青色，白字) */
.status-completed-order { background-color: #4CAF50; color: #FFFFFF; } /* 6=订单完成 (标准绿，白字) */

.cancel-button {
  padding: 0.6rem 1.2rem;
  background-color: #dc3545;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s ease;
}

.cancel-button:hover {
  background-color: #c82333;
}

.view-details-button {
  padding: 0.6rem 1.2rem;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s ease;
  margin-right: 0.5rem; /* Add some spacing if there are other buttons */
}

.view-details-button:hover {
  background-color: #0056b3;
}

.comment-button {
  padding: 0.6rem 1.2rem;
  background-color: #6f42c1; /* Purple */
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s ease;
  margin-left: 0.5rem;
}

.comment-button:hover {
  background-color: #563d7c;
}

.report-maintenance-button {
  padding: 0.6rem 1.2rem;
  background-color: #FF9800; /* Orange */
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s ease;
  margin-left: 0.5rem;
}

.report-maintenance-button:hover {
  background-color: #FB8C00;
}

.filter-controls {
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-controls label {
  font-weight: bold;
  color: #555;
}

.filter-controls select {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 1rem;
  cursor: pointer;
  background-color: #fff;
}

.filter-controls select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}



h2 {
  text-align: center;
  color: #333;
  margin-bottom: 2rem;
  font-size: 2rem;
}

h3 {
  color: #0056b3;
  margin-bottom: 1rem;
  font-size: 1.25rem;
}

.all-bookings-section {
  background: #fff;
  border-radius: 10px;
  padding: 1.5rem;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.filter-controls {
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-controls label {
  font-weight: bold;
  color: #555;
}

.filter-controls select {
  padding: 8px 14px;
  border-radius: 6px;
  border: 1px solid #ccc;
  font-size: 1rem;
  background: #fff;
}

.no-bookings {
  text-align: center;
  padding: 2rem;
  color: #888;
  font-size: 1rem;
}

.no-bookings img {
  width: 60px;
  margin-bottom: 10px;
  opacity: 0.5;
}

.booking-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.booking-item {
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-left: 5px solid #2196F3;
  border-radius: 10px;
  padding: 1.2rem;
  margin-bottom: 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  transition: box-shadow 0.2s ease;
}

.booking-item:hover {
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.1);
}

.booking-details p {
  margin: 0.3rem 0;
  color: #333;
  font-size: 0.95rem;
}

.status-tag {
  display: inline-block;
  padding: 0.4em 0.8em;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 600;
  background-color: #e0e0e0;
  color: #333;
}

.status-pending-payment { background-color: #ffe5e5; color: #d32f2f; }
.status-paid-unused { background-color: #e3f2fd; color: #1976d2; }
.status-refunded { background-color: #eeeeee; color: #616161; }
.status-invalid { background-color: #eceff1; color: #455a64; }
.status-pending-refund { background-color: #fff8e1; color: #f57c00; }
.status-in-use { background-color: #e0f7fa; color: #0097a7; }
.status-completed-order { background-color: #e8f5e9; color: #388e3c; }

.booking-actions {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  min-width: 110px;
}

.action-button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-button.view {
  background-color: #007bff;
  color: white;
}

.action-button.cancel {
  background-color: #dc3545;
  color: white;
}

.action-button.comment {
  background-color: #6f42c1;
  color: white;
}

.action-button.report {
  background-color: #ff9800;
  color: white;
}

.action-button:hover {
  opacity: 0.85;
}

</style>
